package com.qianbao.service.xianwan.impl;

import com.qianbao.components.excepion.CommonException;
import com.qianbao.dao.xianwan.XianWanDao;
import com.qianbao.domain.xianwan.XianWanEntity;
import com.qianbao.service.coinrecord.CoinRecordService;
import com.qianbao.service.money.CoinService;
import com.qianbao.service.user.SVUserService;
import com.qianbao.service.xianwan.XianWanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class XianWanServiceImpl implements XianWanService {

    @Autowired
    private XianWanDao dao;

    @Autowired
    private SVUserService userService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private CoinRecordService recordService;



    @Override
    @Transactional
    public void saveDeviceOrder(XianWanEntity entity) throws CommonException {

        String deviceId = entity.getDeviceid();

        if (deviceId == null || deviceId.length() <= 0){
            throw new CommonException(0,"设备标识号不能为空");
        }


        int num = dao.findIsHaveOrder(entity.getOrdernum());

        if (num > 0){
            // 存在这个订单
            throw new CommonException(1,"订单已接收");
        }else {
            // 不存在这个订单

            // 给用户发奖励
            String customId = userService.findUserCustomIdWithDeviceId(deviceId);

            Double money = Double.valueOf(entity.getMoney()) * 10000;
            int intmoney =  money.intValue();
            String coinNumber = String.valueOf(intmoney);

            coinService.saveUserCoin(customId,coinNumber);

            // 保存订单记录
            recordService.saveCoinRecord(customId,coinNumber,entity.getEvent());

            // 存储订单
            dao.saveDeviceOrder(entity);

        }

    }





}
